<template>
  <div>
    <div class="processstyle">
      <CCard>
        <CCardBody>
          <!-- <Split v-model="split2" mode="vertical" @on-moving="onMoveing"   @on-move-end="onMoveEnd">-->
          <Split v-model="split2" mode="vertical">
            <div slot="top" class="demo-split-pane" ref="boxHeight">
              <div class="mapDiv">
                <div class="dpMapControllWrapper">
                  <div id="dqmap" ref="themap"></div>
                </div>
              </div>
            </div>
            <div slot="bottom" class="demo-split-pane">
              <div style="padding: 0 10px; height: 100%">
                <Table
                  stripe
                  highlight-row
                  ref="currentRowTable"
                  :columns="columns"
                  :data="items"
                  border
                  class="ggg"
                >
                  <template slot="show_dataName" slot-scope="{ row, index }">
                    <!-- <span v-html="getDataName(row)"></span>-->
                    <span>{{ row.processingShowName }}</span>
                  </template>
                  <template slot="show_details4" slot-scope="{ row, index }">
                    <div v-if="row.status == 8 || row.status == 1">
                      <CSelect
                        :disabled="
                          $store.getters.getBtnProcessPriority &&
                          $store.getters.getBtnProcessPriority.enableFlag == '1'
                        "
                        horizontal
                        :options="priorityShowList"
                        :value.sync="row.priority"
                        class="prioritySelect1 selectStyle"
                        @change="selectPriorityChange($event, row)"
                        data-permission="Btn_Process_Priority"
                      ></CSelect>
                    </div>
                    <div v-else>{{ row.priority == 0 ? "普通" : "优先" }}</div>
                  </template>
                  <template slot="status_details" slot-scope="{ row, index }">
                    <button v-if="row.status == 1" class="stastusBtn executing">
                      执行中
                    </button>
                    <button v-if="row.status == 2" class="stastusBtn pause">
                      暂停
                    </button>
                    <button v-if="row.status == 3" style="color: #f9b115">
                      删除
                    </button>
                    <button v-if="row.status == 4" class="stastusBtn success">
                      完成
                    </button>
                    <button
                      v-if="row.status == 5"
                      class="stastusBtn"
                      style="background-color: #ed4014"
                    >
                      失败
                    </button>
                    <button v-if="row.status == 6" style="color: #f9b115">
                      超时
                    </button>
                    <button v-if="row.status == 7" class="stastusBtn stop">
                      停止
                    </button>
                    <button v-if="row.status == 8" class="stastusBtn pending">
                      待执行
                    </button>
                    <button v-if="row.status == -1" class="stastusBtn pending">
                      待创建
                    </button>
                  </template>
                  <template slot="progress_item" slot-scope="{ row, index }">
                    <Progress :percent="row.process" class="cprocssstyle">
                      <span>{{ row.process + "%" }}</span>
                    </Progress>
                  </template>
                  <template slot="show_details2" slot-scope="{ row, index }">
                    <!-- <CButton
                      v-if="row.status == -1"
                      class="textBtnStyle system-btn-style"
                      title="修改"
                      :disabled="!row.startWorkflowId"
                      variant="outline"
                      @click="modifyMonitor(row)"
                      >修改</CButton
                    >
                    <CButton
                      :disabled="true"
                      v-if="row.status != -1"
                      class="disableTextBtnStyle"
                      title="修改"
                      variant="outline"
                      @click="() => {}"
                      data-permission="Btn_Process_Down"
                      >修改</CButton
                    > -->
                    <!-- <CButton
                      class="textBtnStyle system-btn-style"
                      title="定位"
                      :disabled="!row.region"
                      variant="outline"
                      @click="imgRegionFix(row)"
                      >定位</CButton
                    > -->
                    <CButton
                      class="textBtnStyle system-btn-style"
                      title="监控"
                      :disabled="!row.startWorkflowId"
                      variant="outline"
                      @click="showMonitor(row)"
                      >监控</CButton
                    >
                    <CButton
                      v-if="row.status == 4"
                      class="textBtnStyle system-btn-style"
                      title="下载"
                      variant="outline"
                      @click="downloadTaskResult(row)"
                      data-permission="Btn_Process_Down"
                      >下载</CButton
                    >
                    <CButton
                      :disabled="true"
                      v-if="row.status != 4"
                      class="disableTextBtnStyle"
                      title="下载"
                      variant="outline"
                      @click="() => {}"
                      data-permission="Btn_Process_Down"
                      >下载</CButton
                    >
                    <CButton
                      v-show="row.isHuman == 1"
                      class="textBtnStyle system-btn-style"
                      title="人机交互"
                      variant="outline"
                      @click="getInteractive(row)"
                      data-permission="Btn_Process_MI"
                      >人机交互</CButton
                    >
                    <CButton
                      :disabled="true"
                      v-show="row.isHuman == 0"
                      class="disableTextBtnStyle"
                      title="人机交互"
                      variant="outline"
                      @click="() => {}"
                      data-permission="Btn_Process_MI"
                      >人机交互</CButton
                    >
                    <CButton
                      class="textBtnStyle system-btn-style"
                      title="删除"
                      :disabled="!row.startWorkflowId"
                      variant="outline"
                      @click="getInfo(row)"
                      data-permission="Btn_Process_Del"
                      >删除</CButton
                    >
                  </template>
                </Table>
              </div>
            </div>
          </Split>
        </CCardBody>
        <CCardFooter class="page-item.disabled">
          <CRow>
            <CCol class="footerPage" style>
              <span class="pageContent">
                每页
                <!-- :options="[5, 10, 15, 20, 25]" -->
                <CSelect
                  @change="getVendorId($event)"
                  :options="[15, 50, 100, 300, 500, 1000]"
                  v-model="pageSize"
                  class="selectStyle"
                  style
                />
                条记录。第{{ this.currentPage }}页(总共{{ this.total }}页，{{
                  this.allNum
                }}条记录)
              </span>
              <CPagination
                :activePage.sync="currentPage"
                :pages="total"
                align="end"
                v-if="total != 0"
              />
            </CCol>
          </CRow>
        </CCardFooter>
      </CCard>
    </div>
    <!-- 修改优先级弹窗 -->
    <CModal
      :show.sync="prioShow"
      :closeOnBackdrop="false"
      title="修改优先级"
      centered
    >
      <template #header class="taskExecuteHeader">
        <img
          src="@/assets/icons/modifyred.png"
          alt
          style="width: 43px; height: 43px; margin-top: -4px"
        />
        <p class="delKuangShow">修改优先级</p>
      </template>
      <div class="modalBody">
        <label
          style="margin-right: 41px; display: inline-block; margin-top: 6px"
          >优先级</label
        >
        <RadioGroup
          v-model="priorityData.priority"
          class="m_radio_group"
          style="margin-top: 6px"
        >
          <Radio label="0">普通</Radio>
          <Radio label="1">优先</Radio>
        </RadioGroup>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="prioCancel" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="prioOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </CModal>
    <Modal
      v-model="showdownLoad"
      draggable
      scrollable
      title="下载列表"
      :styles="modalStyle"
      class="downLoadModal"
    >
      <Tree
        @on-select-change="selectTree"
        :data="treeData"
        ref="tree"
        class="demo-tree-render"
        style="overflow: auto"
      ></Tree>
      <template #footer class="footerBtns">
        <CButton @click="showdownLoad = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="downLoadProduct" color="info" class="system-btn-style"
          >下载</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="delShow"
      draggable
      scrollable
      title="删除子任务"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">删除子任务</span>
      </p>
      <div class="modalBody">
        <p>删除子任务时与子任务相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="delOk" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
  </div>
</template>

<script>
import TableList from "@/template/table/TableList";
//flowlodId
const jobLogIds = [];
//每个任务得算法总数
const totalNums = [];
//地图是否加载完毕
const isMapLoaded = 0;
//表格是否加载完毕
const isTableLoaded = 0;
//绘制地图边框变量
const redLineData = [];
const blueLineData = [];
const greenLineData = [];
const tempGreenLineData = [];
const tempRednLineData = [
  [
    [116.368, 39.5149],
    [116.675, 39.5407],
    [116.669, 39.326],
    [116.374, 39.3],
    [116.368, 39.5149],
  ],
];
const blackLineData = [];

//图片相关数据
const imageDataIds = [];
const imageBase64Datas = [];
// end
const items = [];
const fields = [
  {
    label: "序号",
    key: "num",
    _style: "width:80px;background:rgba(241,244,249,1);",
    align: "center",
  },
  // "registered",
  // {
  //   label: "taskcode",
  //   key: "startWorkflowId",
  //   _style: "width:auto;background:rgba(241,244,249,1);",
  //   align: "center"
  // },
  {
    label: "数据名称",
    key: "show_dataName",
    _style: "width:auto;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "优先级",
    key: "show_details4",
    _style: "width:75px;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "状态",
    key: "status_details",
    _style: "width:90px;text-align: center;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "进度",
    key: "progress_item",
    _style: "width:130px;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "开始时间",
    key: "startTime",
    _style: "width:170px;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "结束时间",
    key: "endTime",
    _style: "width:170px;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "用时",
    key: "runTime",
    _style: "width:120px;background:rgba(241,244,249,1);",
    align: "center",
  },
  {
    label: "操作",
    key: "show_details2",
    _style: "width:260px;background:rgba(241,244,249,1);",
    align: "center",
  },
];
export default {
  name: "dataQuery",
  computed: {
    getColumn() {
      return [
        { key: "num", title: "序号", align: "center" },
        { key: "priority", title: "优先级", align: "center" },
        { key: "name", title: "数据名称", align: "center" },
        { key: "progress", title: "进度", align: "center" },
        { key: "createTime", title: "开始时间", align: "center" },
        { key: "endTime", title: "结束时间", align: "center" },
        { key: "", title: "执行时间", align: "center" },
        {
          title: "任务日志",
          slot: "action",
          align: "center",
        },
        {
          title: "操作",
          slot: "action2",
          align: "center",
        },
      ];
    },
  },
  data() {
    return {
      userName: "",
      split2: 0.7, //分割面板
      columns: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center",
        },
        {
          title: "数据名称",
          key: "show_dataName",
          slot: "show_dataName",
          minWidth: 250,
        },
        {
          title: "优先级",
          key: "show_details4",
          slot: "show_details4",
          align: "center",
          width: 120,
        },
        {
          title: "状态",
          key: "status_details",
          slot: "status_details",
          align: "center",
          width: 90,
        },
        {
          title: "进度",
          key: "progress_item",
          slot: "progress_item",
          align: "center",
          width: 150,
        },
        {
          title: "开始时间",
          key: "startTime",
          align: "center",
          width: 190,
        },
        {
          title: "结束时间",
          key: "endTime",
          align: "center",
          width: 190,
        },
        {
          title: "用时",
          key: "runTime",
          align: "center",
          width: 110,
        },
        {
          title: "操作",
          key: "show_details2",
          slot: "show_details2",
          align: "center",
          width: 300,
        },
      ],

      modalStyle: { top: "200px" },
      // 修改优先级弹窗
      prioShow: false,
      priorityData: {
        priority: "0",
        startWorkflowId: "",
      },
      currentToken: window.sessionStorage.getItem("PIECloud-Token"),
      productpath: "",
      showdownLoad: false,
      treeData: [],
      taskFlowId: "",
      delShow: false,
      hidedown: true,
      showdown: false,
      startWorkflowId: "",
      hasHuman: false,
      priorityShowList: [
        {
          label: "优先",
          value: 1,
        },
        {
          label: "普通",
          value: 0,
        },
      ],
      globalLineData: [], //所有的图框坐标
      drawDataTotal: [],
      // WebSocket 避免重复连接
      lockReconnect: false, //避免重复连接
      //心跳检测
      heartCheck: {
        timeout: 3000, //每隔三秒发送心跳
        num: 3, //3次心跳均未响应重连
        timeoutObj: null,
        serverTimeoutObj: null,
        start: function () {
          var _this = this;
          var _num = this.num;
          this.timeoutObj && clearTimeout(this.timeoutObj);
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
          this.timeoutObj = setTimeout(function () {
            //这里发送一个心跳，后端收到后，返回一个心跳消息，
            //onmessage拿到返回的心跳就说明连接正常
            // _this.websock.send("心跳包"); // 心跳包
            _num--;
            //计算答复的超时次数
            if (_num === 0) {
              _this.websock.colse();
            }
          }, this.timeout);
        },
      },

      // 返回的图片的地址和信息  地图显示图片 start
      thumbPNGbig: "",
      thumbPNGsmall: "",
      map: null,

      currentPage: 1,
      pages: 0,
      total: 0,
      allNum: 1,
      pageSize: 15,
      taskId: 0,
      items: items.map((item, id) => {
        return { ...item, id };
      }),
      fields,
      details: [],
      collapseDuration: 0,
      showPop: false,
      setting: {
        check: {
          enable: true,
          nocheckInherit: false,
          chkboxType: { Y: "p", N: "s" },
        },
        data: {
          simpleData: {
            enable: true,
          },
        },
        callback: {
          beforeClick: this.beforeClick,
          onClick: this.zTreeOnClick,
          onCheck: this.zTreeOnCheck,
        },
        startWorkflowId: "",
        id: "",
        websock: null,
      },
      websock: null,
      setTime: "",
    };
  },
  watch: {
    items(newVal, oldVal) {
      this.$nextTick(function () {
        this.GlobalPermissionRender.render();
      });
    },
    pageSize(newVal, oldVal) {
      this.routerAfter();
    },
    currentPage(newVal, oldVal) {
      this.currentPage = newVal;
      this.routerAfter();
    },
  },
  beforeDestroy(to, from, next) {
    if (this.map) {
      this.map.remove();
    }
  },
  mounted() {
    let that = this;
    // 加载处理加工界面，检索框显示
    this.userName = window.sessionStorage.getItem("user");
    this.$store.commit("setHeaderSation", "yessearch");
    this.currentToken = window.sessionStorage.getItem("PIECloud-Token");

    this.initMap();
    this.routerAfter();
  },
  components: {
    TableList,
  },
  created() {
    //页面刚进入时开启刷新
    // this.initWebSocket();
  },
  methods: {
    imgRegionFix(row) {
      console.log(row, "row");
    },
    /*   onMoveing() {
      this.getWidth=getComputedStyle( this.$refs.boxHeight , null)["width"];
     this.getHeight=getComputedStyle( this.$refs.boxHeight , null)["height"];
      this.$refs.themap.style.height = this.getHeight;
    },
    onMoveEnd() {
      this.getWidth=getComputedStyle( this.$refs.boxHeight , null)["width"];
      this.getHeight=getComputedStyle( this.$refs.boxHeight , null)["height"];
      this.$refs.themap.style.height = this.getHeight;
    },
*/
    routerAfter() {
      debugger;
      // alert("router");
      if (this.$route.query.from === "taskLook") {
        this.taskId = this.$route.query.id;
        this.allChildrenTask(this.$route.query.id, this.$route.query.status);
      } else if (this.$route.query.from === "taskChildren") {
        this.taskId = this.$route.query.taskId;
        this.onlyChildrenTask(this.$route.query.id);
      } else if (this.$route.query.from === "processingCommon") {
        this.search();
        // 重新渲染左侧树 暂时注掉,修改左侧栏重复渲染时顺序发生变化,如有bug再次解开
        if (this.$parent.$parent.$parent.getTreeList) {
          this.$parent.$parent.$parent.getTreeList(2);
        }
      } else {
        this.search();
      }
    },
    //刷新时进入
    search() {
      let self = this;
      if (!this.currentToken) return;
      let path = this.$api.processingApi.queryLatest;

      let params = {
        pageSize: self.pageSize,
        pageNum: self.currentPage,
        userName: this.userName ? this.userName : "",
      };
      let needWs = false;
      // 当前用户最新主任务的所有子任务
      this.http.get(path, params).then((res) => {
        if (res.data.code == 0) {
          let tempnum = [];
          if (res.data.data.dataList.length < 1) return;
          let temp = res.data.data.dataList;
          self.allNum = res.data.data.total;
          self.data = res.data.data.dataList;
          self.total = Math.ceil(res.data.data.total / self.pageSize);
          for (let i = 0; i < temp.length; i++) {
            if (
              temp[i].status == -1 ||
              temp[i].status == 1 ||
              (temp[i].status == 8 && !needWs)
            ) {
              needWs = true;
            }
            let temps = temp[i];
            //数据字段特殊处理
            temps.num = (self.currentPage - 1) * self.pageSize + i + 1;
            temps.startWorkflowId = temps.taskCode;
            // temps.interactive = self.isHumanTask(temps.taskCode);
            temps.dataName = temps.dataName ? temps.dataName : "";
            temps.startTime = temps.startTime ? temps.startTime : "";
            temps.endTime = temps.endTime ? temps.endTime : "";
            temps.runTime = temps.runTime ? temps.runTime : "";
            if (temp[0].process > 100) {
              temps.process = 100;
            }
            // if (temps.process < 100) {
            //   self.initWebSocket();
            // }
            tempnum.push(temps);
          }

          this.taskId = temp[0].groupTaskId;

          this.items = tempnum;
          // alert("1");
          self.taskDetailResult(this.taskId);

          // 用于控制左侧栏样式
          this.$store.commit("changeLeftPathStyleData", {
            secondLevel: res.data.data.secondLevel,
            thirdLevelId: res.data.data.thirdLevelId,
          });
          if (needWs) {
            this.initWebSocket();
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //查询主任务的所有子任务
    allChildrenTask(id, status) {
      let self = this;
      let params = {
        userId: 0,
        pageSize: self.pageSize,
        pageNum: self.currentPage,
      };
      let path = this.$api.processingApi.query + `/${id}`;
      this.taskId = id;

      this.http.get(path, params).then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.dataList.length < 1) return;
          let temp = res.data.data.dataList;

          self.allNum = res.data.data.total;
          self.total = Math.ceil(res.data.data.total / self.pageSize);

          let tempnum = [];
          for (let i = 0; i < temp.length; i++) {
            let temps = temp[i];
            //数据字段特殊处理
            temps.num = (self.currentPage - 1) * self.pageSize + i + 1;
            temps.startWorkflowId = temp[i].taskCode;
            // temps.interactive = 0;

            temps.processtime = temps.processtime ? temps.processtime : "";
            temps.startTime = temps.startTime ? temps.startTime : "";
            temps.endTime = temps.endTime ? temps.endTime : "";
            temps.runTime = temps.runTime ? temps.runTime : "";
            // if (temps.startWorkflowId != {}) {
            //   temps.interactive = self.isHumanTask(temps.startWorkflowId);
            // }
            if (temps.process > 100) {
              temps.process = 100;
            }
            tempnum.push(temps);
          }
          //用于控制左侧栏样式
          // self.$store.commit("changeLeftPathStyleData", {
          //   secondLevel: "",
          //   thirdLevelId: ""
          // });
          if (res.data.data.secondLevel) {
            self.$store.commit("changeLeftPathStyleData", {
              secondLevel: res.data.data.secondLevel,
              thirdLevelId: res.data.data.thirdLevelId,
            });
          } else {
            self.$store.commit("changeLeftPathStyleData", {
              secondLevel:
                res.data.data.levelMap && res.data.data.levelMap.secondLevel
                  ? res.data.data.levelMap.secondLevel
                  : "",
              thirdLevelId:
                res.data.data.levelMap && res.data.data.levelMap.thirdLevelId
                  ? res.data.data.levelMap.thirdLevelId
                  : "",
            });
          }

          self.taskDetailResult(id);
          self.items = tempnum;
          if (status != 4 && status != 5) {
            self.initWebSocket();
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //子任务跳转 查询具体任务信息
    onlyChildrenTask(id) {
      let self = this;
      let path = this.$api.processingApi.queryInfo + `/${id}`;
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          let temps = res.data.data;
          this.taskId = temps.groupTaskId;
          let tempnum = [];
          //数据特殊字段处理
          temps.num = 1;
          temps.startWorkflowId = temps.taskCode;
          // temps.interactive = 0;

          temps.startTime = temps.startTime ? temps.startTime : "";
          temps.endTime = temps.endTime ? temps.endTime : "";
          temps.runTime = temps.runTime ? temps.runTime : "";

          // if (temps.startWorkflowId != {}) {
          //   temps.interactive = self.isHumanTask(temps.startWorkflowId);
          // }
          if (temps.process > 100) {
            temps.process = 100;
          } else {
            self.queryByTaskDetailId(id);
          }

          if (temps.status != 4 && temps.status != 5) {
            self.initWebSocket();
          }
          tempnum.push(temps);
          this.items = tempnum;

          //用于控制左侧栏样式  返回的数据格式有可能不一样
          if (res.data.data.secondLevel) {
            self.$store.commit("changeLeftPathStyleData", {
              secondLevel: res.data.data.secondLevel,
              thirdLevelId: res.data.data.thirdLevelId,
            });
          } else {
            self.$store.commit("changeLeftPathStyleData", {
              secondLevel:
                res.data.data.levelMap && res.data.data.levelMap.secondLevel
                  ? res.data.data.levelMap.secondLevel
                  : "",
              thirdLevelId:
                res.data.data.levelMap && res.data.data.levelMap.thirdLevelId
                  ? res.data.data.levelMap.thirdLevelId
                  : "",
            });
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },

    selectPriorityChange(event, item) {
      let self = this;
      let priority = event.target.value;
      let startWorkflowId = item.startWorkflowId;

      let url =
        self.$api.processingApi.updateTask + startWorkflowId + "/" + priority;
      this.http
        .put(url)
        .then((res) => {
          if (res.data.code == 0) {
            this.$Message.success("修改成功");
          } else {
            this.$Message.error(res.data.message);
          }
          // 修改后 刷新table
          // self.search()  //查询当前用户的最新的主任务下的所有子任务
          this.routerAfter();
        })
        .catch((err) => {
          this.$Message.error("修改失败");
        });
    },
    prioCancel() {
      this.prioShow = false;
    },
    prioOk() {
      let url =
        this.$api.processingApi.updateTask +
        this.priorityData.startWorkflowId +
        "/" +
        this.priorityData.priority;

      this.http
        .put(url)
        .then((res) => {
          if (res.data.code == 0) {
            this.prioShow = false;
            this.$Message.success("修改成功");
            // 修改成功后 刷新table
            // self.search()  //查询当前用户的最新的主任务下的所有子任务
            this.routerAfter();
          } else {
            this.$Message.error(res.data.message);
          }
        })
        .catch((err) => {
          this.prioShow = false;
          this.$Message.error("修改失败");
        });
    },
    changePriority(data) {
      this.priorityDataNew = `${data.priority}`;
      this.prioShow = true;
      this.priorityData.startWorkflowId = data.startWorkflowId;
    },
    getDataName(item) {
      if (item.imageNumber == 1) {
        return item.dataName;
      } else {
        return item.taskName;
      }
    },
    // 树选择名称，传递名称
    // 复选
    // selectTree(arr,obj) {
    //   let datalength = arr.length
    //   let newarr = [];
    //   for (let i = 0; i < datalength; i++) {
    //     if(arr[i].path != null){
    //       let temp = arr[i].path;
    //       newarr.push(temp);
    //     }

    //   }
    //   this.productpath = newarr.toString();
    //   this.productpath = this.$refs.tree.getSelectedNodes()[0].path;
    // },
    selectTree() {
      let item = this.$refs.tree.getSelectedNodes()[0];
      if (!item) return;
      this.productpath = this.$refs.tree.getSelectedNodes()[0].path;
      if (item.type === "folder") {
        item.expand = !item.expand;
        item.selected = !item.selected;
        return;
      }
    },
    // 产品下载  客户端下载
    // downloadTaskResult(item) {
    //   this.taskFlowId = item.id;
    //   // this.getdownLoad();
    //   let path =
    //     this.$api.taskManageApi.getDetailProductFileByChildId + item.id;
    //   let param = { userName: this.userName };
    //   this.http.get(path, param).then((res) => {
    //     if (res.data.code == 0) {
    //       let data = res.data.data;
    //       let filePath = data.isFile ? data.file : data.file + "/";
    //       let url =
    //         "DownloadFile://" +
    //         sessionStorage.getItem("PIECloud-Token") +
    //         "/" +
    //         this.userName +
    //         "/" +
    //         filePath +
    //         "/";
    //       if (data.isUserFile) {
    //         let r = window.confirm("暂无影像产品数据,是否跳转根目录？");
    //         if (r) {
    //           this.$$openDownLoadFile(url);
    //         }
    //       } else {
    //         this.$$openDownLoadFile(url);
    //       }
    //     } else {
    //       this.$Message.error(res.data.message);
    //     }
    //   });
    // },
    /**树列表下载  暂时勿删*/
    downloadTaskResult(item) {
      let _this = this;
      let path = this.$api.processingApi.downLoad + item.id;
      let params = {
        /*productType: 2,*/
        productType: -1,
      };
      this.http.get(path, params).then((res) => {
        if (res.data.code == 0) {
          if (res.data.data.length < 1) {
            this.$Message.warning("暂无影像产品数据");
          } else {
            _this.showdownLoad = true;
            _this.treeData = _this.getNewTreeData(res.data.data);
          }
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    //提取文件夹里面所有的文件
    getNewTreeData(data) {
      let _this = this;
      let result = [];
      for (let i = 0; i < data.length; i++) {
        let tempItem = data[i];
        let item = tempItem;

        result.push(item);
        if (tempItem.type == "folder" && tempItem.children) {
          let list = [];
          _this.recursiveTreeFile(tempItem.children, list);
          item.children = list;
        }
      }
      return result;
    },

    recursiveTreeFile(data, list) {
      let _this = this;
      for (let i = 0; i < data.length; i++) {
        let tempItem = data[i];
        if (tempItem.type == "file") {
          list.push(tempItem);
        }
        if (tempItem.type == "folder" && tempItem.children) {
          _this.recursiveTreeFile(tempItem.children, list);
        }
      }
      return list;
    },
    // 下载产品
    downLoadProduct() {
      if (!this.productpath) {
        this.$Message.warning("请选择下载的产品文件");
        return;
      }
      /*
      let data = {
        path: this.$api.processingApi.isExit,
        params: {
          username: this.$store.state.user.userName,
          path: this.productpath,
          //path:"/pie/data/247/sthx_user_data/pieadmin/lilintest/123/GF3_KAS_QPSI_010970_E81.2_N40.5_20180910_L1A_VH_L10003442728.tif" //测试地址
        },
      };
      let fun = function () {
        let url =
          "DownloadFile://" +
          sessionStorage.getItem("PIECloud-Token") +
          "/" +
          data.params.username +
          "/" +
          data.params.path +
          "/";
        window.location.href = url;
      };
      this.$$downLoadFile(data, fun);
    */
      let newarr = [];
      newarr.push(this.productpath);
      let path = this.$api.processingApi.downloadReport + newarr;
      window.open(path);
    },

    getInfo(val) {
      this.delShow = true;
      this.startWorkflowId = val.startWorkflowId;
    },
    delOk() {
      this.delShow = false;
      let path = this.$api.processingApi.delete + this.startWorkflowId;
      this.http.delete(path).then((res) => {
        if (res.data.code == 0) {
          this.$Message.success(res.data.message);
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    getVendorId(event) {
      let tempdata = event.target.value; //获取option对应的value值
      this.pageSize = parseInt(tempdata);
    },
    initMap() {
      this.map = new mapboxgl.Map({
        container: "dqmap", // container id
        // style:
        //   "http://121.36.21.73:20002/api/pie-cloud/layerData/layerTemplates?id=2c92808c71bafa7a01720c80d12f010c&key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoie1widXNlcklkXCI6XCIxMDFcIixcImtleVwiOlwiOTBjNGI5NDI0N2FiMThmYmRiZTMyZDc4NzBkMTVjN2JcIn0ifQ.ifWlOcwmtenARlro-tf9hdLDlXjmbIa2T5AwSvRQB-M",
        style: "./static/map/map.json",
        // simple, //四维地球
        // "http://121.36.21.73:20002/api/pie-cloud/layerData/layerTemplates?id=2c92808c71bafa7a01720c80d12f010c&key=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoie1widXNlcklkXCI6XCIxMDFcIixcImtleVwiOlwiOTBjNGI5NDI0N2FiMThmYmRiZTMyZDc4NzBkMTVjN2JcIn0ifQ.ifWlOcwmtenARlro-tf9hdLDlXjmbIa2T5AwSvRQB-M", // stylesheet location
        center: [106.4, 24.5],
        zoom: 3, // starting zoom
        minZoom: 3,
        epsg: 3857,
        doubleClickZoom: false,
      }); //TODO:修改版的mapbox.js需要加入的回调方法

      // this.$nextTick(() => {
      // this.map.on("load", () => {
      //   this.routerAfter();
      // });
      // });
    },

    // getIntermediateInfo() {
    //   let that = this;
    //   let path = that.$api.processingApi.search;
    //   let taskIdList = that.taskIdList;
    //   for (let i in taskIdList) {
    //     let tempTaskId = taskIdList[i];
    //     let param = {
    //       taskId: tempTaskId,
    //       _loadingContainer: document.querySelector(".c-main"),
    //     };
    //     that.http.get(path, param).then((res) => {
    //       let data = res.data;
    //       if (data.success) {
    //         var content = data.data;
    //         if (content && content.length > 0) {
    //           for (var i = 0; i < content.length; i++) {
    //             var imageInfoXml = content[i].imageInfo;
    //             var imageColor = content[i].imageColor;
    //             var lineData = that.parseXml(imageInfoXml);
    //             var base64Str = content[i].base64Str;
    //             //base64码不为空，且之前没有添加过
    //             if (base64Str && imageDataIds.indexOf(content[i].id) < 0) {
    //               var imageBase64 = {
    //                 id: content[i].id,
    //                 lineData: lineData,
    //                 base64Str: base64Str,
    //               };
    //               imageDataIds.unshift(content[i].id);
    //               imageBase64Datas.unshift(imageBase64);
    //             }

    //             if (lineData && lineData.length > 0) {
    //               if (imageColor == "red") redLineData.unshift(lineData);
    //               else if (imageColor == "green")
    //                 greenLineData.unshift(lineData);
    //               else if (imageColor == "blue") blueLineData.unshift(lineData);
    //               else if (imageColor == "black")
    //                 blackLineData.unshift(lineData);
    //               else redLineData.unshift(lineData);
    //             }
    //           }
    //         }
    //       } else {
    //       }
    //     });
    //   }
    // },

    drawPolygon() {
      let that = this;
      // 红绿框的数据源
      let _Greengeojson = {
        type: "FeatureCollection",
        features: [],
      };
      let _Redgeojson = {
        type: "FeatureCollection",
        features: [],
      };

      for (let h = 0; h < that.drawDataTotal.length; h++) {
        let lineColor = that.drawDataTotal[h].imageColor;
        let lineId = that.drawDataTotal[h].algTaskId;
        let imageArr = JSON.parse(that.drawDataTotal[h].imageInfo);

        //添加缩略图图层与获取原始（red）和结果(green)线框范围
        if (lineColor == "green") {
          for (let r = 0; r < imageArr.length; r++) {
            //线框绘制范围 (缩略图实际范围)
            let lineCoordinate = this.getLineCoordinate(imageArr[r]);
            let dd = lineCoordinate.toString().split(",");
            let ar = dd.filter((ele) => {
              return ele !== "0";
            });
            //避免线框的坐标是空，都为0的情况
            if (ar.length < 1) continue;
            that.globalLineData.push(lineCoordinate);
            //缩略图的贴图范围
            let tempImgCoordinate =
              this.getExternalRectangCoordinatelOfImg(lineCoordinate);

            let imageData = that.drawDataTotal[h].resultImageThumbList[r];
            that.map.addLayer({
              id: lineId + r + "_image",
              source: {
                type: "image",
                url: imageData,
                coordinates: tempImgCoordinate,
              },
              type: "raster",
            });

            let _tempFeature = {
              type: "Feature",
              epsg: 3857,
              properties: {
                valuecolor: "#ff0000",
              },
              geometry: {
                type: "Polygon",
                coordinates: [lineCoordinate],
              },
            };
            _Greengeojson.features.push(_tempFeature);
          }
        } else if (lineColor == "red") {
          for (let r = 0; r < imageArr.length; r++) {
            //线框绘制范围 (缩略图实际范围)
            let lineCoordinate = this.getLineCoordinate(imageArr[r]);
            let dd = lineCoordinate.toString().split(",");

            let ar = dd.filter((ele) => {
              return ele !== "0";
            });
            //避免线框的坐标是空，都为0的情况
            if (ar.length < 1) continue;
            that.globalLineData.push(lineCoordinate);

            let _tempFeature = {
              type: "Feature",
              epsg: 3857,
              properties: {
                valuecolor: "#ff0000",
              },
              geometry: {
                type: "Polygon",
                coordinates: [lineCoordinate],
              },
            };
            _Redgeojson.features.push(_tempFeature);
          }
        }
      }

      //添加线框
      this.addLineLayer("redlineid", _Redgeojson); //原始影像范围
      this.addLineLayer("greenline", _Greengeojson); //结果影像范围

      //地图缩放
      let obj = this.getLatestZommAndCenter();

      this.map.flyTo({
        center: obj.center,
        zoom: obj.zoom, // 缩放比例
      });
    },
    //数组去重
    unique(arr) {
      let hash = [];
      for (let i = 0; i < arr.length; i++) {
        if (hash.indexOf(arr[i]) === -1) {
          hash.push(arr[i]);
        }
      }
      return hash;
    },
    //取缩略图的外界矩形作为缩略图的显示范围（缩略图是倾斜的，实际有一个矩形图）
    getExternalRectangCoordinatelOfImg(imageCoordinate) {
      let long = []; //经度
      let lat = []; //纬度
      imageCoordinate.forEach((element) => {
        long.push(element[0]);
        lat.push(element[1]);
      });
      long = this.unique(long);
      lat = this.unique(lat);
      let minX = Math.min(...long);
      let minY = Math.min(...lat);
      let maxX = Math.max(...long);
      let maxY = Math.max(...lat);
      //绘制缩略图需要四个点坐标  绘制线框需要5个点坐标
      let result = [
        [minX, maxY],
        [maxX, maxY],
        [maxX, minY],
        [minX, minY],
      ];
      return result;
    },
    //获取线框绘制范围
    getLineCoordinate(data) {
      let result = [
        [data.topLeftLongitude, data.topLeftLatitude],
        [data.topRightLongitude, data.topRightLatitude],
        [data.bottomRightLongitude, data.bottomRightLatitude],
        [data.bottomLeftLongitude, data.bottomLeftLatitude],
        [data.topLeftLongitude, data.topLeftLatitude],
      ];
      return result;
    },
    //获取最新的缩放比例和地图中心点
    getLatestZommAndCenter() {
      // 计算 并 移动到中心点
      let that = this;
      let minGlobalX = 180,
        minGlobalY = 90,
        maxGlobalX = -180,
        maxGlobalY = -90;

      for (var i = 0; i < that.globalLineData.length; i++) {
        let gLineData = that.globalLineData[i];
        if (gLineData.length <= 0) continue;

        for (let j = 0; j < gLineData.length; j++) {
          if (minGlobalX > parseFloat(gLineData[j][0])) {
            minGlobalX = parseFloat(gLineData[j][0]);
          }
          if (maxGlobalX < parseFloat(gLineData[j][0])) {
            maxGlobalX = parseFloat(gLineData[j][0]);
          }
          if (minGlobalY > parseFloat(gLineData[j][1])) {
            minGlobalY = parseFloat(gLineData[j][1]);
          }
          if (maxGlobalY < parseFloat(gLineData[j][1])) {
            maxGlobalY = parseFloat(gLineData[j][1]);
          }
        }
      }
      let centerGlobalX = 0;
      let centerGlobalY = 0;
      if (maxGlobalX === -180 && minGlobalX === 180) {
        centerGlobalX = 116.4;
        centerGlobalY = 39.9;
      } else {
        centerGlobalX = (minGlobalX + maxGlobalX) / 2;
        centerGlobalY = (minGlobalY + maxGlobalY) / 2;
      }

      let centermoddle = [];
      centermoddle.push(centerGlobalX);
      centermoddle.push(centerGlobalY);
      //视图范围比数据范围大20%
      let viewWidth = 0;
      let viewHeight = 0;
      if (maxGlobalX === -180 && minGlobalX === 180) {
        viewWidth = (minGlobalX - maxGlobalX) * 1.2;
        viewHeight = (minGlobalY - maxGlobalY) * 1.2;
      } else {
        viewWidth = (maxGlobalX - minGlobalX) * 1.2;
        viewHeight = (maxGlobalY - minGlobalY) * 1.2;
      }

      let ratio = Math.sqrt(Math.sqrt(Math.sqrt(2))); //视图范围每扩大或缩小ratio倍，缩放等级对应减少或增加0.125

      let indexX = 6; //初始缩放等级为7
      let zoomBaseX = 5.96; //缩放等级为7时，经度范围为5.96
      if (viewWidth > zoomBaseX) {
        //如果实际范围比基准范围大，基准范围按比例扩大，直至大于实际范围，获取此时缩放等级
        while ((zoomBaseX = zoomBaseX * ratio) < viewWidth) {
          indexX -= 0.125;
        }
      } else {
        //如果实际范围比基准范围小，基准范围按比例缩小，直至小于实际范围，获取此时缩放等级
        while ((zoomBaseX = zoomBaseX / ratio) > viewWidth) {
          indexX += 0.125;
        }
      }

      let indexY = 6; //初始缩放等级为7
      let zoomBaseY = 1.91; //缩放等级为7时，纬度范围为1.91
      if (viewHeight > zoomBaseY) {
        while ((zoomBaseY = zoomBaseY * ratio) < viewHeight) {
          indexY -= 0.125;
        }
      } else {
        while ((zoomBaseY = zoomBaseY / ratio) > viewHeight) {
          indexY += 0.125;
        }
      }

      //在经纬度分别获取的缩放等级中，获取比较小的值作为缩放等级，确保数据能完全显示
      let index = indexX < indexY ? indexX : indexY;
      let result = { center: centermoddle, zoom: index };
      return result;
    },
    //添加线框图层
    addLineLayer(id, geoGson) {
      let that = this;

      that.map.addSource(id, {
        //原始影像边框
        type: "geojson",
        data: geoGson,
      });
      if (id === "redlineid") {
        that.map.addLayer({
          id: "RedLineId",
          type: "line",
          source: id,

          layout: {},
          paint: {
            "line-color": "red",
            "line-width": 1,
            "line-opacity": 0.8,
          },
        });
      } else if (id === "greenline") {
        that.map.addLayer({
          id: "GreenLineId",
          type: "line",
          source: id,

          layout: {},
          paint: {
            "line-color": "green",
            "line-width": 1,
            "line-opacity": 0.8,
          },
        });
      }
    },

    // 解析xml获取数据边框四点坐标
    parseXml(str) {
      if (!str || str.length <= 0) {
        return null;
      } else {
        //创建文档对象
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(str, "text/xml");

        //提取数据
        let metaData = $(xmlDoc).find("ProductMetaData");
        let topLeftLon = $(metaData).find("TopLeftLongitude")[0].textContent;
        let topLeftLat = $(metaData).find("TopLeftLatitude")[0].textContent;
        let topRightLon = $(metaData).find("TopRightLongitude")[0].textContent;
        let topRightLat = $(metaData).find("TopRightLatitude")[0].textContent;
        let bottomLeftLon = $(metaData).find("BottomLeftLongitude")[0]
          .textContent;
        let bottomLeftLat =
          $(metaData).find("BottomLeftLatitude")[0].textContent;
        let bottomRightLon = $(metaData).find("BottomRightLongitude")[0]
          .textContent;
        let bottomRightLat = $(metaData).find("BottomRightLatitude")[0]
          .textContent;
        var data = [
          [topLeftLon, topLeftLat],
          [topRightLon, topRightLat],
          [bottomRightLon, bottomRightLat],
          [bottomLeftLon, bottomLeftLat],
          [topLeftLon, topLeftLat],
        ];
        return data;
      }
    },
    //创建绘制框线DataSet
    createLineDataSet(lineData) {
      var dataLine = {
        type: "FeatureCollection",
        features: [],
      };
      for (var i = 0; i < lineData.length; i++) {
        var dataLineSet = {
          type: "Feature",
          geometry: {
            type: "LineString",
            coordinates: lineData[i],
          },
        };
        dataLine.features.push(dataLineSet);
      }
      return dataLine;
    },
    clearLayer(layerId) {
      //清除图层
      if (!this.map.getLayer(layerId)) {
      } else {
        this.map.removeLayer(layerId);
      }
      if (!this.map.getSource(layerId)) {
      } else {
        this.map.removeSource(layerId);
      }
    },
    // WebSocket 实现页面数据的刷新 start
    //初始化weosocket
    initWebSocket() {
      let webSocket = "";
      if (window.location.href.split(":")[0] === "http") {
        webSocket = "ws://";
      }
      if (window.location.href.split(":")[0] === "https") {
        webSocket = "wss://";
      }
      // let wsuri = "";
      // if (
      //   this.$api.processingApi.webSocketUrl.indexOf(window.location.host) != -1
      // ) {
      //   wsuri = webSocket + this.$api.processingApi.webSocketUrl;
      // } else {
      const wsuri =
        webSocket + window.location.host + this.$api.processingApi.webSocketUrl;
      // }
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    //连接建立之后执行send方法发送数据
    websocketonopen() {
      // this.websocketsend();
      let userId = window.sessionStorage.getItem("userId");
      let msg =
        '{"userId": ' +
        userId +
        ',"taskId": ' +
        this.taskId +
        ',"type": "task","topic":"conn"}';

      this.websocketsend(msg);
      //心跳检测重置
      // this.heartCheck.start();
    },
    //连接建立失败重连
    websocketonerror(e) {
      this.reconnect();
    },
    websocketonmessage(e) {
      let self = this;
      //拿到任何消息都说明当前连接是正常的
      // self.heartCheck.start();
      const redata = JSON.parse(e.data);

      if (redata.type == "websocket_progress") {
        for (let i = 0; i < self.items.length; i++) {
          if (redata.content.taskDetailId !== self.items[i].id) continue;
          // 加工处理进度的更新
          if (redata.content.progress != self.items[i].process) {
            self.items[i].process = redata.content.progress;
          }
          // 加工处理状态的更新
          if (redata.content.status != self.items[i].status) {
            self.items[i].status = redata.content.status;
          }
          self.items[i].startWorkflowId = redata.content.taskCode;
          // 加工处理开始时间的更新
          if (redata.content.startTime != "") {
            self.items[i].startTime = redata.content.startTime;
          }
          // 加工处理结束时间的更新
          if (redata.content.endTime != "") {
            self.items[i].endTime = redata.content.endTime;
          }
          // 加工处理运行时间的更新
          if (redata.content.runTime != "") {
            self.items[i].runTime = redata.content.runTime;
          }
        }
      } else if (redata.type == "websocket_metedata") {
        self.queryByTaskDetailId(redata.content.taskDetailId);
        // if (redata) {
        //   let content = redata.content;
        //   //解析WebSocket发送过来的Json数据
        //   let imageInfoXml = content.metadata;
        //   self.testparseXml(imageInfoXml);
        //   // self.testparseXml();
        //   let base64Str = content.thumbPNGbig.info;
        //   let lineid = "'" + content.taskDetailId + "'";
        //   // self.tempGreenLineData = lineData;
        //   // self.drawPolygon(base64Str);
        //   // let lineid = "testline"
        //   self.drawPolygon(lineid, base64Str);
        // } else {
        //   // 不处理
        // }
      } else if (redata.type == "websocket_error") {
        console.log("建立连接异常信息", redata.content);
        this.websock.close();
      }
    },
    //数据发送
    websocketsend(Data) {
      this.websock.send(Data);
    },
    //关闭
    websocketclose(e) {
      this.websock.close();
    },

    // 重连操作，通过设置lockReconnect变量避免重复连接
    reconnect() {
      let self = this;
      if (self.lockReconnect) {
        return;
      }
      self.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      tt && clearTimeout(tt);
      var tt = setTimeout(function () {
        self.initWebSocket();
        self.lockReconnect = false;
      }, 5000);
    },

    // 解析xml获取数据边框四点坐标
    testparseXml(str) {
      // let str = '<?xmlversion="1.0"encoding="UTF-8"?>'+"<ProductMetaData><SatelliteID>GF1</SatelliteID><SensorID>PMS1</SensorID><ReceiveTime>2013-11-2703:20:09</ReceiveTime><OrbitID>3173</OrbitID><ProduceType>STANDARD</ProduceType><SceneID>169510</SceneID><ProductID>117600</ProductID><ProductLevel>LEVEL1A</ProductLevel><ProductQuality/><ProductQualityReport/><ProductFormat>GEOTIFF</ProductFormat><ProduceTime>2013-11-2713:27:18</ProduceTime><Bands>5</Bands><ScenePath>1</ScenePath><SceneRow>179</SceneRow><SatPath>605</SatPath><SatRow>179</SatRow><SceneCount>1</SceneCount><SceneShift>1</SceneShift><StartTime>2013-11-2711:20:06</StartTime><EndTime>2013-11-2711:20:12</EndTime><CenterTime>2013-11-2711:20:09</CenterTime><ImageGSD>2</ImageGSD><WidthInPixels>18192</WidthInPixels><HeightInPixels>18000</HeightInPixels><WidthInMeters/><HeightInMeters/><CloudPercent>0</CloudPercent><QualityInfo></QualityInfo><PixelBits></PixelBits><ValidPixelBits></ValidPixelBits><RollViewingAngle>0</RollViewingAngle><PitchViewingAngle>0</PitchViewingAngle><RollSatelliteAngle>4.00976e-06</RollSatelliteAngle><PitchSatelliteAngle>-0.000168794</PitchSatelliteAngle><YawSatelliteAngle>2.93532</YawSatelliteAngle><SolarAzimuth>169.012</SolarAzimuth><SolarZenith>28.7088</SolarZenith><SatelliteAzimuth>88.2337</SatelliteAzimuth><SatelliteZenith>88.2309</SatelliteZenith><GainMode>G4</GainMode><IntegrationTime>0.000289101</IntegrationTime><IntegrationLevel>S1</IntegrationLevel><MapProjection/><EarthEllipsoid/><ZoneNo/><ResamplingKernel/><HeightMode/><MtfCorrection>LAB</MtfCorrection><RelativeCorrectionData></RelativeCorrectionData><TopLeftLatitude>39.6149</TopLeftLatitude><TopLeftLongitude>116.368</TopLeftLongitude><TopRightLatitude>39.5407</TopRightLatitude><TopRightLongitude>116.775</TopRightLongitude><BottomRightLatitude>39.226</BottomRightLatitude><BottomRightLongitude>116.679</BottomRightLongitude><BottomLeftLatitude>39.3</BottomLeftLatitude><BottomLeftLongitude>116.274</BottomLeftLongitude><TopLeftMapX/><TopLeftMapY/><TopRightMapX/><TopRightMapY/><BottomRightMapX/><BottomRightMapY/><BottomLeftMapX/><BottomLeftMapY/></ProductMetaData>"
      if (!str || str.length <= 0) {
        return null;
      } else {
        //创建文档对象
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(str, "text/xml");
        xmlDoc.async = false;
        //提取数据
        var metaData = $(xmlDoc).find("ProductMetaData");
        var topLeftLon = Number(
          $(metaData).find("TopLeftLongitude")[0].textContent
        );
        var topLeftLat = Number(
          $(metaData).find("TopLeftLatitude")[0].textContent
        );
        var topRightLon = Number(
          $(metaData).find("TopRightLongitude")[0].textContent
        );
        var topRightLat = Number(
          $(metaData).find("TopRightLatitude")[0].textContent
        );
        var bottomLeftLon = Number(
          $(metaData).find("BottomLeftLongitude")[0].textContent
        );
        var bottomLeftLat = Number(
          $(metaData).find("BottomLeftLatitude")[0].textContent
        );
        var bottomRightLon = Number(
          $(metaData).find("BottomRightLongitude")[0].textContent
        );
        var bottomRightLat = Number(
          $(metaData).find("BottomRightLatitude")[0].textContent
        );
        let data = [
          [topLeftLon, topLeftLat],
          [topRightLon, topRightLat],
          [bottomRightLon, bottomRightLat],
          [bottomLeftLon, bottomLeftLat],
          [topLeftLon, topLeftLat],
        ];
        this.tempGreenLineData = data;
        return data;
      }
    },

    //清除框线数据
    clearLineData() {
      let self = this;
      self.redLineData = [];
      self.greenLineData = [];
      self.blueLineData = [];
      self.blackLineData = [];

      for (let i = 0; i < self.imageDataIds.length; i++) {
        let layerId = self.imageDataIds[i];
        if (map.getLayer(layerId)) {
          map.remove(map.getLayer(layerId));
        }
      }
      self.imageDataIds = [];
      self.imageBase64Datas = [];
    },

    toggleDetails(item) {
      this.$set(this.items[item.id], "_toggled", !item._toggled);
      this.collapseDuration = 300;
      this.$nextTick(() => {
        this.collapseDuration = 0;
      });
    },

    // 1.子任务id
    queryByTaskDetailId(data) {
      let self = this;
      let path = this.$api.processingApi.queryByTaskDetailId + data;
      let param = {
        productType: 0,
        // _loadingContainer: document.querySelector(".container")
      };
      self.drawDataTotal = [];
      this.http.get(path, param).then((res) => {
        if (res.data.success && res.data.data.length > 0) {
          self.drawDataTotal = res.data.data;
          self.drawPolygon();
        }
      });
    },
    // 2.主任务id
    taskDetailResult(data) {
      let self = this;
      let path = this.$api.processingApi.taskDetailResult + data;
      let param = {
        productType: 0,
        // _loadingContainer: document.querySelector(".container")
      };
      self.drawDataTotal = [];
      this.http.get(path, param).then((res) => {
        if (res.data.success && res.data.data.length > 0) {
          self.drawDataTotal = res.data.data;
          self.drawPolygon();
        }
      });
    },
    // end
    // 详情-任务日志
    showDetails(id) {
      this.$router.replace("/Detail");
    },
    showMonitor(data) {
      if (data.id && data.startWorkflowId && data.status && data.taskName) {
        let path = `/taskManage/taskDetails/${data.id}/${data.startWorkflowId}/${data.status}/${data.taskName}`;
        this.$router.push({ path: path });
      } else {
        this.$Message.warning("请等待任务创建完成!");
      }
    },

    // 人机交互
    getInteractive(taskCode) {
      let myToken = this.currentToken;
      let startWorkflowId = taskCode.startWorkflowId;

      let path =
        this.$api.processingApi.childTaskWorkFlow +
        startWorkflowId +
        "/isHumanTaskInProgress";
      this.http.get(path).then((res) => {
        if (res.data.code == 0) {
          let taskId = res.data.data.taskId;
          this.$Message.success(res.data.message);
          let url = "";
          if (res.data.data.algId == "piesat.humantask.measure") {
            //点位量测
            url = "imageinteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.drafting") {
            //专题制图
            url = "CartoInteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.sampling") {
            //参量样本选择
            url = "classifiedinteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.check") {
            //人工质检
            url = "checkinteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.mosaic") {
            // 影像镶嵌
            url = "MosaicInteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.qamodel") {
            //  产品质量分析模块
            url = "QAModelInteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.spatial") {
            //  空间分析与制图
            url = "SpatialInteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId == "piesat.humantask.dataloader") {
            url = "DataLoaderInteractive://" + myToken + "/" + taskId + "/";
          } else if (res.data.data.algId.includes("piesat.humantask")) {
            let name = res.data.data.algId.split('.')[2];
            url = name + "Interactive://" + myToken + "/" + taskId + "/";
          }
          if (url == "") return;

          window.location.href = url;
        } else {
          this.$Message.error(res.data.message);
        }
      });
    },
    // 判断当前任务是否有人机交互
    // isHumanTask(taskCode) {
    //   //多个任务时，判断是否人工交互，需要同步判断保存至items数据
    //   let self = this;
    //   let result = 0;
    //   let startWorkflowId = taskCode;
    //   let path =
    //     self.$api.processingApi.childTaskWorkFlow +
    //     startWorkflowId +
    //     "/isHumanTaskInProgress";

    //   $.ajax({
    //     type: "GET",
    //     async: false, // fasle同步，true异步
    //     headers: { Authorization: this.currentToken },
    //     contentType: "application/json;charset=UTF-8",
    //     url: path,
    //     success: function (res) {
    //       if (res.code == 1) {
    //         result = 0;
    //       } else {
    //         result = 1;
    //       }
    //     },
    //     error: function (e) {
    //       console.log(e.status);
    //     },
    //   });

    //   return result;
    // },
  },
  activated() {
    this.initMap();
  },
  destroyed: function () {
    //页面销毁时关闭长连接
    if (this.websock != null) {
      this.websock.close();
    }
    // clearInterval(this.theInterval);
  },
};
</script>

<style scoped>
.py-2 {
  display: flex;
}
.ivu-table-cell {
  padding-left: 0px;
  padding-right: 0px;
}
.tableStyle td {
  padding: 0px;
}
.cprocssstyle {
  height: 15px;
  margin-left: 2px;
  margin-right: 2px;
}
/* 表格中进度的颜色 */
.ivu-progress-success .ivu-progress-bg {
  background-color: #67b9a5;
}
</style>
<style lang="less">
.dpMapControllWrapper {
  margin: 11px 12px;
  height: 100%;
  #dqmap {
    width: 100% !important;
    height: calc(100vh - 100px);
    position: relative;
    border: 1px solid #ddd;
    border-top: none;
  }
  .ivu-modal-mask /deep/ {
    z-index: 2000 !important;
  }
  .ivu-modal-wrap /deep/ {
    z-index: 2000 !important;
  }
}
.processTable {
  padding: 0 0.75rem;
}
.hoverstyle:hover {
  background-color: rgba(0, 0, 0, 0.2);
}
.page-item.disabled {
  cursor: pointer;
}
.pageContent {
  margin-right: 26px;
  font-size: 14px;
}
.selectStyle {
  display: inline-block;
  width: 100px;
  margin-right: 5px;
}
.footerPage {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
  color: black;
}
</style>
<style scoped>
.processstyle /deep/ .card-footer {
  bottom: 9px;
}
.ggg {
  height: 100%;
}
/deep/.ivu-table-body {
  height: calc(100% - 40px);
  overflow-y: auto;
  overflow-x: auto;
}
/deep/.card-body {
  position: static !important;

  padding: 0;
}
/deep/.ivu-split-pane.top-pane {
  overflow: hidden;
  margin-bottom: 10px;
}
/deep/.ivu-split-wrapper {
  height: calc(100% - 62px);
}
/deep/.demo-split-pane {
  height: 100%;
}
/deep/ ::-webkit-scrollbar {
  height: 0px;
}

/deep/.mapboxgl-canvas-container {
  height: 100%;
}

/deep/ .mapboxgl-canvas-container .mapboxgl-canvas {
  height: 100%;
}
/deep/.page-item.active .page-link {
  background-color: var(--label-font-color, #5d8bc4);
}
.selectStyle {
  margin: 0;
}
/deep/.form-control {
  padding: 0;
}
</style>
